package de.dhbw.ka.tit09.picsim.model;

import java.util.LinkedList;

import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.observable.list.WritableList;

import de.dhbw.ka.tit09.picsim.RealmProvider;

/**
 * Model of the PIC stack.
 * 
 * @author Andreas Bender
 * 
 */
public class PICStack extends WritableList {
	private int buffer;
	private volatile boolean run;

	/**
	 * Constructor.
	 */
	public PICStack() {
		super(Realm.getDefault(), new LinkedList<Integer>(), Integer.class);
	}

	/**
	 * Initializes the stack.
	 */
	public void initStack() {
		run = false;

		RealmProvider.getUIRealm().exec(new Runnable() {
			public void run() {
				clear();
				run = true;
			}
		});

		while (!run) {
		}
	}

	/**
	 * Pushes a new program address to the stack.
	 * 
	 * @param value the instruction address
	 */
	public void push(final int value) {
		run = false;

		RealmProvider.getUIRealm().exec(new Runnable() {
			public void run() {
				add(0, value);
				run = true;
			}
		});

		while (!run) {
		}
	}

	/**
	 * Returns the highest program address on the stack.
	 * 
	 * @return the upper stack element
	 */
	public int pop() {
		run = false;

		RealmProvider.getUIRealm().exec(new Runnable() {
			public void run() {
				buffer = (Integer) remove(0);
				run = true;
			}
		});

		while (!run) {
		}

		return buffer;
	}
}
